package collection_test.queue.blcok_queue;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 阻塞队列 DelayQueue   按照时间进行排序  可用于调度任务  xx时间后执行某任务。。
 */
public class DelayQueueTest {
    public static void main(String[] args) {
        DelayQueue delayQueue = new DelayQueue();
        delayQueue.add(new Task("t1", 4000));
        delayQueue.add(new Task("t2", 9000));
        delayQueue.add(new Task("t3", 2000));
        delayQueue.add(new Task("t4", 4000));
        delayQueue.add(new Task("t5", 500));
        for (int i = 0; i < 5; i++) {
            System.out.println(delayQueue.poll());
        }

    }

    static class Task implements Delayed {
        String name;
        long runningTime;

        public Task(String name, long runningTime) {
            this.name = name;
            this.runningTime = runningTime;
        }

        @Override
        public long getDelay(TimeUnit unit) {
            return unit.convert(runningTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
        }

        @Override
        public int compareTo(Delayed o) {
            if (this.getDelay(TimeUnit.MILLISECONDS) < o.getDelay(TimeUnit.MILLISECONDS))
                return -1;
            else if (this.getDelay(TimeUnit.MILLISECONDS) > o.getDelay(TimeUnit.MILLISECONDS))
                return 1;
            else
                return 0;
        }

        @Override
        public String toString() {
            return "Task{" +
                    "name='" + name + '\'' +
                    ", runningTime=" + runningTime +
                    '}';
        }
    }
}
